package com.heiye.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.heiye.pojo.StudentInfo;
import com.heiye.service.StudentInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

@RestController
public class LoginController {

    @Autowired
    private StudentInfoService studentInfoService;

    /**
     * 学生登录
     *
     * @param jsonObject
     * @return 0:登陆失败   1:登陆成功
     */
    @PostMapping("/login")
    public int login(@RequestBody JSONObject jsonObject) {
        String stuId = jsonObject.getString("stuId");
        String stuPassword = jsonObject.getString("stuPassword");
        int type = jsonObject.getInteger("type");
        System.out.println(stuId);
//        if (type == 2) {
//            //学生登陆
//            QueryWrapper<StudentInfo> queryWrapper = new QueryWrapper<>();
//            queryWrapper.eq("stu_id", stuId);
//            queryWrapper.eq("stu_password", stuPassword);
//
//            //登陆失败
//            if (studentInfoService.getOne(queryWrapper) == null) {
//                return 0;
//            }
//            return 1;
//        }
//        return 0;

        return 1;
    }

    @PostMapping("save")
    public int savePicture(@RequestParam("file")MultipartFile file,@RequestParam("id")String id) throws IOException {

        //如果文件不存在上传失败
        if (file.isEmpty()) {
            System.out.println("文件不存在");
           return 0;
        }
        //获取文件名字
        String fileName = file.getOriginalFilename();
        //设置编译后文件存在路径
        String path = ClassUtils.getDefaultClassLoader().getResource("").getPath()+"static/photo/";
        //获取项目路径
        File directory = new File("src/main/resources/static/photo");
        String paths = directory.getCanonicalPath();

        File dest = new File(paths+'/' + fileName);
        System.out.println(dest.getAbsoluteFile());

        FileInputStream fileInputStream = (FileInputStream) file.getInputStream();
        //以流的方式上传
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(path + File.separator + fileName));
        byte[] bs = new byte[1024];
        int len;
        while ((len = fileInputStream.read(bs)) != -1) {
            bos.write(bs, 0, len);
        }
        bos.flush();
        bos.close();

        try {
            //文件上传
            file.transferTo(dest);
            return 1;
        } catch (IOException e) {
        }


        return 1;
    }
}
